<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>redux</title>
</head>
<body>
<div id="root">

</div>
<script>
  function createStore(reducer) {
    // 定义一个初试状态
    let state = null

    // 定义一个数组，存放一组在状态发生变化的时候处理的业务
    let listeners = []

    function subscribe(fn) {
      listeners.push(fn)
    }

    function dispatch(action) {
      // reducer, 来源与reduce, 是个纯函数
      state = reducer(state, action)

      // 触发listener里的函数
      listeners.forEach(fn => fn())
    }

    function getState() {
      return state
    }

    // 自己调用一次dispatch, 目的是初始化状态
    dispatch({
      type: '4o5zxlaqeruozlr'
    })

    return {
      dispatch,
      getState,
      subscribe
    }
  }

  const defaultState = {
    count: 0
  }

  function reducer(state, action) {
    // 初始化state
    if (!state) {
      state = defaultState
    }

    switch(action.type) {
      case 'add':
        // 返回一个新的state
        return {
          count: state.count + 1
        }
      case 'minus':
        return {
          count: state.count - 1
        }
      default:
        return state
    }
  }

  const store = createStore(reducer)

  function renderDOM() {
    document.querySelector('#root').innerHTML = store.getState().count
  }

  store.subscribe(renderDOM)

  setInterval(() => {
    store.dispatch({
      type: 'add'
    })
  }, 1000)
  

</script>
</body>
</html>